package com.zhku.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhku.entity.Appointable_list;
import com.zhku.entity.Appointment;
import com.zhku.entity.User;
import com.zhku.entity.Vaccinum;
import com.zhku.openservice.UserOpenService;
import com.zhku.openservice.VacciOpenService;
import com.zhku.service.IAppointableListService;
import com.zhku.service.IAppointmentService;
import com.zhku.service.IVaccinumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @BelongsProject: SpringBoot_School_Work
 * @BelongsPackage: com.zhku.controller
 * @Author: "deweyMDH"
 * @CreateTime: 2023-04-07  19:31
 * @Version: 1.0
 */
@RestController
@RequestMapping(value = "/appointableList")
public class AppointableListController {
    // 自动装配
    @Autowired
    IAppointableListService appointableListService;

    @Autowired
    IAppointmentService appointmentService;

    @Autowired
    IVaccinumService vaccinumService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    VacciOpenService vacciOpenService;

    @Autowired
    UserOpenService userOpenService;

    //使用jackson来转换map
    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @description: 可携带一个地点关键字，进行查询预约的信息
     * @author: deweyMDH
     * @param: [pageNum, pageSize, keyword]
     * @return: java.lang.String
     **/
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(
            @RequestParam(required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(required = true, defaultValue = "1") Integer pageSize,
            @RequestParam(required = false, defaultValue = "") String keyword, //关键词
            @RequestParam(required = false, defaultValue = "") String condition
    ) throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
        //分页查询
        /*分页构造函数
        Params:
        current – 当前页
        size – 每页显示条数*/

        //查询构造条件
        QueryWrapper<Appointable_list> queryWrapper = new QueryWrapper<>();
        // 成立的表达式，字段名 和数值
        if (condition.equals("address")){
            queryWrapper.like(keyword != null && !keyword.equals(""), "address", keyword);
        } else if (condition.equals("appDate")){
            queryWrapper.like(keyword != null && !keyword.equals(""), "app_date", keyword);
        } else {

        }
        Page<Appointable_list> page = appointableListService.page(new Page<>(pageNum, pageSize), queryWrapper);
        page.getRecords().forEach(en -> {
            // 利用 Appointable_list 的疫苗id，查到疫苗名称，并设回 Appointable_list
            // 直接使用RestTemplate 原生进行服务调度，其实服务调度都算不上，单纯就是后端发送请求，获取别的服务的数据
//            Vaccinum vaccinum = restTemplate.getForObject("http://localhost:8085/vaccinum/getOne/" + en.getVaccinumId(), Vaccinum.class);
            // 使用了nacos 服务注册中心，有了服务调度的概念，服务调度就是按照服务名进行，服务之间的通信，比原生的没有固定端口和ip，灵活了更多
//            Vaccinum vaccinum = restTemplate.getForObject("http://vecisystem-vacci/vaccinum/getOne/" + en.getVaccinumId(), Vaccinum.class);
            // 使用了 OpenFeign ,进一步实现了功能的独立，使得根据每个服务可以独立管理起来。
            Vaccinum vaccinum = vacciOpenService.getOne(en.getVaccinumId());
            en.setVaccinum(vaccinum);
        });
        // 在结果中放一个list集合
        result.put("list", page.getRecords());
        result.put("total", page.getTotal());
        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description: 查询疫苗中的疫苗种类，提供前端选择
     * @author: deweyMDH
     * @param: []
     * @return: java.lang.String
     **/
    @RequestMapping(value = "/listType", method = RequestMethod.GET)
    public String listType() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();

        List<Vaccinum> list = vacciOpenService.getAll();
        if (list != null) {
            result.put("ok", true);
            result.put("list", list);
        } else {
            result.put("ok", false);
            result.put("message", "查询疫苗数量错误");
        }

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description: 新增一个预约类型
     * @author: deweyMDH
     * @param: [appointableList]
     * @return: java.lang.String
     **/
    @PostMapping(value = "/insert")
    public String insertAppointable(Appointable_list appointableList) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        boolean one = appointableListService.save(appointableList);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointableList", appointableList);
        } else {
            result.put("ok", false);
            result.put("message", "错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description:    新增一个具体的预约记录
     * @author: deweyMDH
     * @param: [appointment]
     * @return: java.lang.String
     **/
    @PostMapping(value = "/insAppointment")
    public String insertAppointment(Appointable_list appointableList, HttpSession session) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        Appointment appointment = new Appointment();
        User user = (User)session.getAttribute("user");

        appointment.setUserId(user.getId());
        appointment.setVaccinumId(appointableList.getVaccinumId());
        appointment.setAddress(appointableList.getAddress());
        appointment.setAppDate(appointment.getAppDate());
        // 创建一个此刻的时间，格式是 yy-mm-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String PostTime = sdf.format(now);
        appointment.setPostTime(PostTime);

        appointment.setStatus(0);
        // 查询所有的医护人员
        List<User> role = userOpenService.getRole();
        User userDoc = role.get(new Random().nextInt(role.size()));
        appointment.setDocId(userDoc.getId());

        boolean save = appointmentService.save(appointment);
        // 设置某场次，某时间的某种疫苗的预约数加一，剩余量-1
        appointableList.setAppNum(appointableList.getAppNum() + 1);
        appointableList.setNums(appointableList.getNums() - 1);
        // 修改预约列表的数据
        boolean one = appointableListService.updateById(appointableList);
        //判断数据库是否有数据
        if (save!= false && one != false) {
            result.put("ok", true);
            result.put("appointment", appointment);
        } else {
            result.put("ok", false);
            result.put("message", "错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }


    /**
     * @description: 修改预约记录的数据
     * @author: deweyMDH
     * @param: [appointableList]
     * @return: java.lang.String
     **/
    @PutMapping(value = "/update")
    public String updateAppointList(Appointable_list appointableList) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        boolean one = appointableListService.updateById(appointableList);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointableList", appointableList);
        } else {
            result.put("ok", false);
            result.put("message", "修改预约类型错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description: 根据主键，删除相应的预约类型
     * @author: deweyMDH
     * @param: [Id]
     * @return: java.lang.String
     **/
    @DeleteMapping(value = "/delete/{id}")
    public String deleteAppointList(@PathVariable(value = "id") Integer Id) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        boolean one = appointableListService.removeById(Id);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointableList", Id);
        } else {
            result.put("ok", false);
            result.put("message", "删除预约类型错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }
}
